	package com.sap.mobile.maf.samples.android.mafprovisioningsample;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import java.util.HashMap;

import com.sap.maf.tools.logon.logonapi.LogonContext;
import com.sap.maf.tools.logon.logonapi.LogonContext.LogonProcessEnum;
import com.sap.maf.tools.logon.logonapi.LogonContextListener;
import com.sap.maf.tools.logon.logonmanager.LogonManager;
import com.sap.maf.tools.logon.logonmanager.LogonManager.LogonManagerException;
import com.sap.maf.tools.logon.logonui.LogonView;
import com.sap.maf.uicontrols.MAFSkinManager;
import com.sap.maf.uicontrols.view.MAFToast;
import com.sap.maf.utilities.logger.MAFLogger;
import com.sybase.mo.MessagingClientException;

public class LogonActivity extends Activity implements LogonContextListener {
	private LogonView logonView;
	private final String TAG = "LogonActivity";
	Intent returnIntent = new Intent();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setResult(LockScreenActivity.logonRequestCode, returnIntent);
		createUI();
	}

	private void createUI() {
		final SharedPreferences localPrefs = getSharedPreferences(
				getPackageName() + "_preferences", MODE_PRIVATE);
		final String styleName = localPrefs.getString("themeID", "Default");
		Context ctx = this;
		try {
			MAFSkinManager.getInstance(this).setActiveStyle(styleName);
		} catch (IllegalArgumentException e) {
			// $JL-EXC$
		}
		// Initialize the Logon UI
		logonView = new LogonView(ctx);
		// Show the logon screen
		setContentView(logonView);

		
		try {
			handleLogon();
		} catch (LogonManagerException e) {
			MAFLogger.e(TAG, e.getMessage(), e);
		}
	}

	/**
	 * Check wether the user is already logged in. If not start onboarding
	 * otherwise give back the control to the application
	 * 
	 * @throws LogonManagerException
	 */
	private void handleLogon() throws LogonManagerException {
		LogonManager.setManualLogonSelectionAllowed(false);
		LogonContext logonContext = null;
		try {
			logonContext = LogonManager.getLogonContext(this);
		} catch (MessagingClientException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (logonContext.isUserLoggedOn()) {
			returnIntent.putExtra("isUserLoggedOn", true);
			finish();
		}
		logonView.resolveLogonContext(logonContext, this, this);
	}
	

	/**
	 * when all of the supplied credentials were correct, this callback is fired
	 * and we stop the processing dialog and give back the control to the
	 * application
	 */
	@Override
	public void onLogonFinished(LogonContext logonContext) {
		logonView.hideProgress();
		final LogonContext finalLogonContext = logonContext;
		runOnUiThread(new Runnable() {
			public void run() {
				if (finalLogonContext.getLogonProcess().equals(
						LogonProcessEnum.SUP_LOGOUT)) {
//					finalLogonContext.setLogonProcess(LogonProcessEnum.SUP_ACT_CODE);
					returnIntent.putExtra("isUserLoggedOn", false);
					finish();
				} else {
					returnIntent.putExtra("isUserLoggedOn", true);
					finish();
				}
			}
		});
	}



	/**
	 * the login button was pressed on the logon screen, so we show a process
	 * dialog and start the onboarding process
	 */
	@Override
	public void onLogonContextUpdated(final LogonContext logonContext) {
		logonView.showProgress(this);
		new Thread(new Runnable() {
			@Override
			public void run() {
				// Call the onboarding process
				LogonManager.resolveLogonContext(logonContext,
						LogonActivity.this);
			}
		}).start();
	}

	/**
	 * Called when the user registration failed and we inform the user about it
	 */
	@Override
	public void onLogonFailed(LogonContext logonContext, String errorCode,
			Throwable root) {
		logonView.hideProgress();
		final String finalErrorCode = errorCode;
		final Throwable fRoot = root;
		runOnUiThread(new Runnable() {
			public void run() {
				if (LogonView.ERROR_INVALID_INPUT_DATA.equals(finalErrorCode)) {
					// the supplied credetial validation failed
					Toast.makeText(getApplicationContext(),
							"Logon failed, Check input fields!",
							Toast.LENGTH_LONG).show();
				} else {
					String msg = "Logon failed," + fRoot.getMessage(); 
					if (fRoot.getCause() != null){ 
						msg += ", " + fRoot.getCause().getMessage();
					}
					Toast.makeText(getApplicationContext(), msg,
							Toast.LENGTH_LONG).show();
				}
			}
		});
	}

	/**
	 * the cancel button was pressed on the logon screen, meaning the user wants
	 * to exit the application
	 * 
	 */
	@Override
	public void onLogonCanceled(LogonContext context) {
		runOnUiThread(new Runnable() {
            public void run() {
            	Toast.makeText(getApplicationContext(), "Logon canceled", Toast.LENGTH_LONG).show();
            	returnIntent.putExtra("isUserLoggedOn", false);
            	finish();
             }
         });
    }

	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.preferences:
			// open the preferences screen
			startActivityForResult(new Intent(this, SamplePreferenceActivity.class), LockScreenActivity.preferenceRequestCode);
			break;
		default:
			return super.onOptionsItemSelected(item);
		}
		return true;
	}
	@Override
		public boolean onIsServerTrusted(LogonContext logonContext, String certChain) {
		// TODO Auto-generated method stub
		return false;
	}
	
    @Override
    	public boolean onIsServerTrusted(LogonContext logonContext,
			final HashMap<String, String> certChainHashMap) {
        // TODO Auto-generated method stub
        return false;
    }

	@Override
	public boolean onIsPasswordInput() {
		
		runOnUiThread(new Runnable() {
			@Override
			public void run() {			
			logonView.hideProgress();
			logonView.showPassCodeInput();
			}
		});
		
		synchronized(this){
			try {
				this.wait();
			} catch (InterruptedException e) {
				MAFLogger.e(TAG, e.getMessage());
			}
		}
		
		return true;
	}

	@Override
	public void onPasswordGiven() {
		synchronized(this){
			this.notifyAll();
		}
		
	}

	@Override
	public void onPolicyViolation() {
	
		runOnUiThread(new Runnable() {
			@Override
			public void run() {			
				MAFToast.makeText(getApplicationContext(),
						"Password policy has been violated!",
						MAFToast.LENGTH_LONG).show();
			}
		});
		
	
		
	}

}
